﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using SheepStorage.Domain;
using SheepStorage.Domain.DTO.InputDto;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SheepStorage.Service.DataImp
{

    /// <summary>
    /// EarTagService
    /// </summary>
    public class EarTagService : IEarTagService
    {
        private readonly IBaseRepository<EarTagTable> _earTagRepository;
        private readonly SheepDbContext _db;
        private readonly IMapper _mapper;

        public EarTagService(IBaseRepository<EarTagTable> earTagRepository, SheepDbContext db, IMapper mapper)
        {
            _earTagRepository = earTagRepository;
            _db = db;
            _mapper = mapper;
        }
        /// <summary>
        /// 产羔耳标列表
        /// </summary>
        /// <param name="overBit"></param>
        /// <param name="birType"></param>
        /// <param name="birthState"></param>
        /// <param name="useState"></param>
        /// <returns></returns>
        public async Task<PageOutput<EarTagTable>> GetEarTags(int pageIndex, int pageSize, string? overBit, int birType, int birthState, int useState)
        {
            var list = _earTagRepository.GetAll().Where(c => c.IsDel == 0);
            if (!string.IsNullOrEmpty(overBit))
            {
                list = list.Where(c => c.OverBit.Contains(overBit));
            }
            if (birType != -1)
            {
                list = list.Where(c => c.BirType == birType);
            }
            if (birthState != -1)
            {
                list = list.Where(c => c.BirthState == birthState);
            }
            if (useState != -1)
            {
                list = list.Where(c => c.UseState == useState);
            }
            //分页对象
            var result = new PageOutput<EarTagTable>()
            {
                Total=list.Count(),
                PageSize=pageSize,
            };
            //分页
            var elist=list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            result.Data = elist;
            return result;
        }
        /// <summary>
        /// 添加耳标
        /// </summary>
        /// <param name="earTag"></param>
        /// <returns></returns>
        //public int AddEarTags(EarTagTable earTag)
        //{
        //    //var reault= _earTagRepository.Add(earTag);
        //    //return reault;


        //    var Eartags = new List<EarTagTable>();
        //    //如果EarpreFix为空,单个添加,否则批量添加
        //    if (string.IsNullOrEmpty(earTag.EarpreFix))
        //    {
        //        if (earTag.BirType == 1)
        //        {
        //            earTag.OverBit="DB-"+earTag.OverBit;
        //        }
        //        else if (earTag.BirType == 2)
        //        {
        //            earTag.OverBit = "AZB-" + earTag.OverBit;
        //        }
        //        else if (earTag.BirType == 3)
        //        {
        //            earTag.OverBit = "SFK-" + earTag.OverBit;
        //        }
        //        else if (earTag.BirType == 4)
        //        {
        //            earTag.OverBit = "DH-" + earTag.OverBit;
        //        }
        //        else if (earTag.BirType == 5)
        //        {
        //            earTag.OverBit = "DDH-" + earTag.OverBit;
        //        }
        //        else if (earTag.BirType == 6)
        //        {
        //            earTag.OverBit = "ADH-" + earTag.OverBit;
        //        }
        //        else if (earTag.BirType == 7)
        //        {
        //            earTag.OverBit = "AH-" + earTag.OverBit;
        //        }
        //        else if(earTag.BirType == 8)
        //        {
        //            earTag.OverBit = "HY-" + earTag.OverBit;
        //        }
        //        else if (earTag.BirType == 9)
        //        {
        //            earTag.OverBit = "ADH-" + earTag.OverBit;
        //        }
        //        else
        //        {
        //            throw new Exception();
        //        }
        //        var list = _earTagRepository.GetAll().FirstOrDefault(c => c.OverBit == earTag.OverBit);
        //        if (list != null)
        //        {
        //            return -1;
        //        }
        //        Eartags.Add(_mapper.Map<EarTagTable>(earTag));
        //    }
        //    else
        //    {
        //        if(earTag.BirType == 1)
        //        {
        //            earTag.OverBit = "DB-";
        //        }
        //        else if (earTag.BirType == 2)
        //        {
        //            earTag.OverBit = "AZB-";
        //        }
        //        else if (earTag.BirType == 3)
        //        {
        //            earTag.OverBit = "SFK-";
        //        }
        //        else if (earTag.BirType == 4)
        //        {
        //            earTag.OverBit = "DH-";
        //        }
        //        else if (earTag.BirType == 5)
        //        {
        //            earTag.OverBit = "DDH-";
        //        }
        //        else if (earTag.BirType == 6)
        //        {
        //            earTag.OverBit = "ADH-";
        //        }
        //        else if (earTag.BirType == 7)
        //        {
        //            earTag.OverBit = "AH-";
        //        }
        //        else if (earTag.BirType == 8)
        //        {
        //            earTag.OverBit = "HY-";
        //        }
        //        else if (earTag.BirType == 9)
        //        {
        //            earTag.OverBit = "ADH-";
        //        }
        //        else
        //        {
        //            throw new Exception();
        //        }
        //        var start = int.Parse(earTag.OverPrefix);
        //        var end = int.Parse(earTag.OverNumber);
        //        for (int i = start; i <= end; i++)
        //        {
        //            var newEarTag = new EarTagTable();
        //            newEarTag.OverBit = earTag.OverBit.Split('-')[0] + "-" + i;
        //            var list = _earTagRepository.GetAll().FirstOrDefault(c => c.OverBit == newEarTag.OverBit);
        //            if (list != null)
        //            {
        //                return -1;
        //            }
        //            Eartags.Add(_mapper.Map<EarTagTable>(newEarTag));
        //        }
        //    }
        //    return _earTagRepository.AddRange(Eartags);

        //}
        public  async Task<int> AddEarTags(EarTagTable earTag)
        {
            if (earTag == null)
            {
                throw new ArgumentNullException(nameof(earTag));
            }

            var Eartags = new List<EarTagTable>();

            // 根据 BirType 设置 OverBit 的前缀
            switch (earTag.BirType)
            {
                case 1:
                    earTag.OverBit = "DB-" + earTag.OverBit;
                    break;
                case 2:
                    earTag.OverBit = "AZB-" + earTag.OverBit;
                    break;
                case 3:
                    earTag.OverBit = "SFK-" + earTag.OverBit;
                    break;
                case 4:
                    earTag.OverBit = "DH-" + earTag.OverBit;
                    break;
                case 5:
                    earTag.OverBit = "DDH-" + earTag.OverBit;
                    break;
                case 6:
                case 9: // 注意 6 和 9 共用相同前缀 "ADH-"
                    earTag.OverBit = "ADH-" + earTag.OverBit;
                    break;
                case 7:
                    earTag.OverBit = "AH-" + earTag.OverBit;
                    break;
                case 8:
                    earTag.OverBit = "HY-" + earTag.OverBit;
                    break;
                default:
                    throw new ArgumentException("Invalid BirType");
            }

            // 单个添加
            if (earTag.EarpreFix == "1" )
            {
                var existingTag = _earTagRepository.GetAll().FirstOrDefault(c => c.OverBit == earTag.OverBit);
                if (existingTag != null)
                {
                    return -1; // 已存在，返回 -1 表示失败
                }
                Eartags.Add(_mapper.Map<EarTagTable>(earTag));
            }
            else // 批量添加
            {
                var start = int.Parse(earTag.OverPrefix);
                var end = int.Parse(earTag.OverNumber);
                for (int i = start; i <= end; i++)
                {
                    var newEarTag = new EarTagTable()
                    {
                        WarehousingDate = earTag.WarehousingDate,
                        BirthState = earTag.BirthState,
                        BirType = earTag.BirType,     
                        OverBit = earTag.OverBit + "-" + i,
                        ElEarTag=earTag.OverBit+"-"+i,
                        OverPrefix=earTag.OverPrefix,
                        OverNumber=earTag.OverNumber,
                        EarpreFix=earTag.EarpreFix,
                        UseState=1,

                    };
                    var existingTag = _earTagRepository.GetAll().FirstOrDefault(c => c.OverBit == newEarTag.OverBit);
                    if (existingTag != null)
                    {
                        return -1; // 已存在，返回 -1 表示失败
                    }
                    Eartags.Add(_mapper.Map<EarTagTable>(newEarTag));
                }
            }

            return  _earTagRepository.AddRange(Eartags); // 执行批量插入操作
        }
        /// <summary>
        /// 删除耳标
        /// </summary>
        /// <param name="earTagId"></param>
        /// <returns></returns>
        public async Task<int> DelEarTags(int earTagId)
        {
            var list = _earTagRepository.GetInfoBy(earTagId);
            list.IsDel = 1;
            return _earTagRepository.Update(list);
        }
        /// <summary>
        /// 批删耳标
        /// </summary>
        /// <param name="earTagIds"></param>
        /// <returns></returns>
        public async Task<int> BatchDelEarTags(List<int> earTagIds)
        {
            foreach(var id in earTagIds)
            {
                var list = _earTagRepository.GetInfoBy(id);
                list.IsDel = 1;
                _earTagRepository.Update(list);
            }
            return 1;
        }
        /// <summary>
        /// 反填耳标
        /// </summary>
        /// <param name="earTagId"></param>
        /// <returns></returns>
        public async Task<EarTagTable> GetEarTag(int earTagId)
        {
            var list = _earTagRepository.GetInfoBy(earTagId);
            return list;
        }
        /// <summary>
        /// 修改耳标
        /// </summary>
        /// <param name="earTag"></param>
        /// <returns></returns>
        public async Task<int> UpdEarTags(EarTagTable earTag)
        {
            var list=_earTagRepository.GetInfoBy(earTag.EarTagId);
            list.EarTagId = earTag.EarTagId;
            list.WarehousingDate = earTag.WarehousingDate;
            list.BirType = earTag.BirType;
            list.BirthState = earTag.BirthState;
            list.OverBit = earTag.OverBit;
            return _earTagRepository.Update(list);
        }

        public async Task<List<EarTagTable>> GetIdList()
        {
            var earTags = _earTagRepository.GetAll().Where(c => c.IsDel == 0 && c.UseState==1).ToList(); // 获取未删除的耳号数据
            return earTags;
        }
    }

}

